<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>Answer</title>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/babel-regenerator-runtime@6.5.0/runtime.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div class="section" id="app1"></div>
    </div>
    <script type="text/babel">
      let rtc;

      const App = () => {
        const videos = React.useRef([]);
        const [streams, setStreams] = React.useState([]);

        React.useEffect(() => {
          (async () => {
            const socket = new WebSocket("ws://localhost:8888");
            await new Promise((r) => (socket.onopen = r));
            console.log("open websocket");

            const offer = await new Promise(
              (r) => (socket.onmessage = (ev) => r(JSON.parse(ev.data)))
            );
            console.log("offer", offer.sdp);

            const peer = (rtc = new RTCPeerConnection({
              iceServers: [],
            }));
            peer.onicecandidate = ({ candidate }) => {
              if (!candidate) {
                console.log(peer.localDescription.sdp);
                const sdp = JSON.stringify(peer.localDescription);
                socket.send(sdp);
              }
            };
            peer.oniceconnectionstatechange = () => {
              console.log(
                "oniceconnectionstatechange",
                peer.iceConnectionState
              );
            };
            peer.ontrack = (e) => {
              const stream = e.streams[0];
              setStreams((streams) => [...streams, stream]);
            };
            const localStream = await navigator.mediaDevices.getUserMedia({
              video: true,
              audio: false,
            });
            localStream
              .getVideoTracks()
              .forEach((track) => peer.addTrack(track, localStream));

            await peer.setRemoteDescription(offer);
            const answer = await peer.createAnswer();
            await peer.setLocalDescription(answer);

            let times = 0;
            setInterval(async () => {
              if (times++ >= 4) return;

              socket.onmessage = async ({ data }) => {
                const answer = JSON.parse(data);
                console.log("answer", answer.sdp);
                await peer.setRemoteDescription(answer);
              };

              peer.onnegotiationneeded = async () => {
                const answer = await peer.createOffer();
                await peer.setLocalDescription(answer);
              };

              const localStream = await navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false,
              });
              localStream
                .getVideoTracks()
                .forEach((track) => peer.addTrack(track, localStream));
              console.log("re signaling");
            }, 3000);
          })();
        }, []);

        React.useEffect(() => {
          videos.current.forEach((v, i) => {
            v.srcObject = streams[i];
          });
        }, [streams]);

        return (
          <div>
            answer
            <div style={{ display: "flex" }}>
              {streams.map((_, i) => (
                <div key={i}>
                  {i}
                  <video
                    ref={(ref) => {
                      const arr = videos.current;
                      arr[i] = ref;
                      videos.current = arr;
                    }}
                    autoPlay
                    muted
                  />
                </div>
              ))}
            </div>
          </div>
        );
      };

      ReactDOM.render(<App />, document.getElementById("app1"));
    </script>
  </body>
</html>
